//
//  HomeViewController.m
//  美团
//
//  Created by Ansen on 15-3-4.
//  Copyright (c) 2015年 Ansen. All rights reserved.
//

#import "HomeViewController.h"
#import "Const.h"
#import "HomeTopItem.h"
#import "UIBarButtonItem+Extension.h"
#import "UIView+Extension.h"
#import "CategoryViewController.h"
#import "DistrictViewController.h"
#import "SortViewController.h"
#import "Const.h"
#import "City.h"
#import "MetaTool.h"
#import "Sort.h"
#import "Region.h"
#import "Categorys.h"
#import "DPAPI.h"
#import "Deal.h"
#import "MJExtension.h"
#import "DealCell.h"
#import "MJRefresh.h"
#import "NavController.h"
#import "SearchViewController.h"
#import "AwesomeMenu.h"
#import "UIView+AutoLayout.h"
#import "MyCollectViewController.h"
#import "RecentViewController.h"
#import "MBProgressHUD+MJ.h"

@interface HomeViewController ()<AwesomeMenuDelegate>

/** 分类item */
@property(nonatomic, weak) UIBarButtonItem *categortItem;
/** 地区item */
@property(nonatomic, weak) UIBarButtonItem *districtItem;
/** 排序item */
@property(nonatomic, weak) UIBarButtonItem *sortItem;

/** 当前选中的城市 */
@property(nonatomic ,copy) NSString *selectedCityName;
/** 当前选中的分类名字 */
@property (nonatomic, copy) NSString *selectedCategoryName;
/** 当前选中的区域名字 */
@property (nonatomic, copy) NSString *selectedRegionName;
/** 当前选中的排序 */
@property(nonatomic ,strong) Sort *selectedSort;
/** 排序popover */
@property(nonatomic,strong) UIPopoverController *sortPopover;
/** 区域popover */
@property (nonatomic, strong) UIPopoverController *regionPopover;
/** 分类popover */
@property (nonatomic, strong) UIPopoverController *categoryPopover;

@end

@implementation HomeViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 监听城市改变
    [NotificationCenter addObserver:self selector:@selector(cityDidChange:) name:CityDidChangeNotification object:nil];
    // 监听排序改变
    [NotificationCenter addObserver:self selector:@selector(sortDidChange:) name:SortDidChangeNotification object:nil];
    // 监听区域改变
    [NotificationCenter addObserver:self selector:@selector(regionDidChange:) name:RegionDidChangeNotification object:nil];
    [NotificationCenter addObserver:self selector:@selector(categoryDidChange:) name:CategoryDidChangeNotification object:nil];
    
    // 设置导航栏内容
    [self setupLeftNav];
    [self setupRightNav];
    
    // 创建awesomemenu
    [self setupAwesomeMenu];
    

}

#pragma mark - 实现父类提供的方法
-(void)setupParams:(NSMutableDictionary *)params
{
    // 城市
    params[@"city"] = self.selectedCityName;
    // 分类(类别)
    if (self.selectedCategoryName) {
        params[@"category"] = self.selectedCategoryName;
    }
    // 区域
    if (self.selectedRegionName) {
        params[@"region"] = self.selectedRegionName;
    }
    // 排序
    if (self.selectedSort) {
        params[@"sort"] = @(self.selectedSort.value);
    }
}

-(void)dealloc
{
    [NotificationCenter removeObserver:self];
}

- (void)setupAwesomeMenu
{
    // 1.中间的item
    AwesomeMenuItem *startItem = [[AwesomeMenuItem alloc] initWithImage:[UIImage imageNamed:@"icon_pathMenu_background_highlighted"] highlightedImage:nil ContentImage:[UIImage imageNamed:@"icon_pathMenu_mainMine_normal"] highlightedContentImage:nil];
    
    // 2.周边的item
    AwesomeMenuItem *item0 = [[AwesomeMenuItem alloc] initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"] highlightedImage:nil ContentImage:[UIImage imageNamed:@"icon_pathMenu_collect_normal"] highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_collect_highlighted"]];
    AwesomeMenuItem *item1 = [[AwesomeMenuItem alloc] initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"] highlightedImage:nil ContentImage:[UIImage imageNamed:@"icon_pathMenu_collect_normal"] highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_collect_highlighted"]];
    AwesomeMenuItem *item2 = [[AwesomeMenuItem alloc] initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"] highlightedImage:nil ContentImage:[UIImage imageNamed:@"icon_pathMenu_collect_normal"] highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_collect_highlighted"]];
    AwesomeMenuItem *item3 = [[AwesomeMenuItem alloc] initWithImage:[UIImage imageNamed:@"bg_pathMenu_black_normal"] highlightedImage:nil ContentImage:[UIImage imageNamed:@"icon_pathMenu_collect_normal"] highlightedContentImage:[UIImage imageNamed:@"icon_pathMenu_collect_highlighted"]];
    
    NSArray *items = @[item0,item1,item2,item3];
    AwesomeMenu *menu = [[AwesomeMenu alloc] initWithFrame:CGRectZero startItem:startItem optionMenus:items];
    menu.alpha = 0.5;
    // 设置菜单的活动范围
    menu.menuWholeAngle = M_PI_2;
    // 设置开始按钮的位置
    menu.startPoint = CGPointMake(50, 150);
    // 设置代理
    menu.delegate = self;
    // 不要旋转中间按钮
    menu.rotateAddButton = NO;
    [self.view addSubview:menu];
    
    [menu autoPinEdgeToSuperviewEdge:ALEdgeLeft withInset:0];
    [menu autoPinEdgeToSuperviewEdge:ALEdgeBottom withInset:0];
    [menu autoSetDimensionsToSize:CGSizeMake(200, 200)];
}

#pragma mark - AwesomeMenuDelegate
- (void)awesomeMenuWillAnimateOpen:(AwesomeMenu *)menu
{
    // 替换菜单的图片
    menu.contentImage = [UIImage imageNamed:@"icon_pathMenu_cross_normal"];
    
    // 完全显示
    menu.alpha = 1.0;
}

- (void)awesomeMenuWillAnimateClose:(AwesomeMenu *)menu
{
    // 替换菜单的图片
    menu.contentImage = [UIImage imageNamed:@"icon_pathMenu_mainMine_normal"];
    
    // 半透明显示
    menu.alpha = 0.5;
}

- (void)awesomeMenu:(AwesomeMenu *)menu didSelectIndex:(NSInteger)idx
{
    // 替换菜单的图片
    menu.contentImage = [UIImage imageNamed:@"icon_pathMenu_mainMine_normal"];
    
    switch (idx) {
        case 0: { // 收藏
            NavController *nav = [[NavController alloc] initWithRootViewController:[[MyCollectViewController alloc] init]];
            [self presentViewController:nav animated:YES completion:nil];
            break;
        }
            
        case 1: { // 最近访问记录
            NavController *nav = [[NavController alloc] initWithRootViewController:[[RecentViewController alloc] init]];
            [self presentViewController:nav animated:YES completion:nil];
            break;
        }
            
        default:
            break;
    }
}

-(void)sortDidChange:(NSNotification *)notification
{
    self.selectedSort  = notification.userInfo[SelectSort];
    
    // 1.更换顶部区域item的文字
    HomeTopItem *topItem = (HomeTopItem *)self.sortItem.customView;
    [topItem setSubtitle:self.selectedSort.label];
    
    // 2.关闭popover
    [self.sortPopover dismissPopoverAnimated:YES];
    
    // 3.刷新表格数据
    [self.collectionView headerBeginRefreshing];
    
}

-(void)cityDidChange:(NSNotification *)notification
{
    self.selectedCityName  = notification.userInfo[SelectCityName];
    
    // 1.更换顶部区域item的文字
    HomeTopItem *topItem = (HomeTopItem *)self.districtItem.customView;
    [topItem setTitle:[NSString stringWithFormat:@"%@ - 全部",self.selectedCityName ]];
    [topItem setSubtitle:nil];
    
    // 2.刷新表格数据
    [self.collectionView headerBeginRefreshing];
}

- (void)categoryDidChange:(NSNotification *)notification
{
    Categorys *category = notification.userInfo[SelectCategory];
    NSString *subcategoryName = notification.userInfo[SelectSubcategoryName];
    
    if (subcategoryName == nil || [subcategoryName isEqualToString:@"全部"]) {// 点击的数据没有子分类
        self.selectedCategoryName = category.name;
    }else{
        self.selectedCategoryName = subcategoryName;
    }
    
    if ([self.selectedCategoryName isEqualToString:@"全部分类"]) {
        self.selectedCategoryName = nil;
    }
    
    // 1.更换顶部item的文字
    HomeTopItem *topItem = (HomeTopItem *)self.categortItem.customView;
    [topItem setIcon:category.icon highIcon:category.highlighted_icon];
    [topItem setTitle:category.name];
    [topItem setSubtitle:subcategoryName];
    
    // 2.关闭popover
    [self.categoryPopover dismissPopoverAnimated:YES];
    // 3.刷新表格数据
    [self.collectionView headerBeginRefreshing];
}

- (void)regionDidChange:(NSNotification *)notification
{
    NSString *regionName = notification.userInfo[SelectRegionName];
    NSString *subRegionName = notification.userInfo[SelectSubregionName];
    
    if (subRegionName == nil || [subRegionName isEqualToString:@"全部"])  {
        self.selectedRegionName = regionName;
    }else {
        self.selectedRegionName = subRegionName;
    }
    
    if ([self.selectedRegionName isEqualToString:@"全部"]) {
        self.selectedRegionName = nil;
    }
    
    // 1.更换顶部item的文字
    HomeTopItem *topItem = (HomeTopItem *)self.districtItem.customView;
    [topItem setTitle:[NSString stringWithFormat:@"%@ - %@", self.selectedCityName, regionName]];
    [topItem setSubtitle:subRegionName];
    
    // 2.关闭popover
    [self.regionPopover dismissPopoverAnimated:YES];
    
    // 3.刷新表格数据
    [self.collectionView headerBeginRefreshing];
}


#pragma mark - 设置导航栏内容
-(void)setupLeftNav
{
    // 1.LOGO
    UIBarButtonItem *logoItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_meituan_logo"] style:UIBarButtonItemStyleDone target:nil action:nil];
    logoItem.enabled = NO;
    
    // 2.类别
    HomeTopItem *categoryTopItem = [HomeTopItem item];
    [categoryTopItem addTarget:self action:@selector(categoryClick)];
    UIBarButtonItem *categoryItem = [[UIBarButtonItem alloc] initWithCustomView:categoryTopItem];
    _categortItem = categoryItem;

    // 3.地区
    HomeTopItem *districtTopItem = [HomeTopItem item];
    [districtTopItem addTarget:self action:@selector(districtClick)];
    UIBarButtonItem *districtItem = [[UIBarButtonItem alloc] initWithCustomView:districtTopItem];
    _districtItem = districtItem;
    
    // 4.排序
    HomeTopItem *sortTopItem = [HomeTopItem item];
    [sortTopItem setTitle:@"排序"];
    [sortTopItem setIcon:@"icon_sort" highIcon:@"icon_sort_highlighted"];
    [sortTopItem addTarget:self action:@selector(sortClick)];
    UIBarButtonItem *sortItem = [[UIBarButtonItem alloc] initWithCustomView:sortTopItem];
    _sortItem = sortItem;
    
    self.navigationItem.leftBarButtonItems = @[logoItem, categoryItem, districtItem, sortItem];
    
}

#pragma mark - 顶部item点击方法
- (void)categoryClick
{
    // 显示分类菜单
    self.categoryPopover = [[UIPopoverController alloc] initWithContentViewController:[[CategoryViewController alloc] init]];
    [self.categoryPopover presentPopoverFromBarButtonItem:_categortItem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (void)districtClick
{
    DistrictViewController *dirstrictVc = [[DistrictViewController alloc] init];
    if (self.selectedCityName) {
        City *city = [[[MetaTool cities] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name = %@", self.selectedCityName]] firstObject];
        dirstrictVc.regions = city.regions;
    }
    
    // 显示城市
    self.regionPopover = [[UIPopoverController alloc] initWithContentViewController:dirstrictVc];
    [self.regionPopover  presentPopoverFromBarButtonItem:_districtItem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (void)sortClick
{
    SortViewController *vc = [[SortViewController alloc] init];
    // 显示城市
    self.sortPopover = [[UIPopoverController alloc] initWithContentViewController:vc];
    [self.sortPopover presentPopoverFromBarButtonItem:_sortItem permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

-(void)setupRightNav
{
    UIBarButtonItem *map = [UIBarButtonItem itemWithTarget:self action:nil image:@"icon_map" highImage:@"icon_map_highlighted"];
    map.customView.width = 60;
    
    UIBarButtonItem *search = [UIBarButtonItem itemWithTarget:self action:@selector(search) image:@"icon_search" highImage:@"icon_search_highlighted"];
    search.customView.width = 60;
    
    self.navigationItem.rightBarButtonItems = @[map,search];
}

#pragma mark - 顶部item点击方法
- (void)search
{
    if (self.selectedCityName) {
        SearchViewController *vc = [[SearchViewController alloc] init];
        vc.cityName = self.selectedCityName;
        NavController  *nav = [[NavController alloc] initWithRootViewController:vc];
        [self presentViewController:nav animated:YES completion:nil];
    }else{
        [MBProgressHUD showError:@"请选择城市后再搜索" toView:self.view];
    }
 
}




@end
